package common.service.base.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.alibaba.fastjson.JSON;

import common.service.base.annotation.CmsCheckSession;
import common.service.base.annotation.NoCheckSession;
import common.service.base.common.Constant;
import common.service.base.common.MobileSession;
import common.service.base.common.ReqHeader;
import common.service.base.common.SessionInfo;
import common.service.base.exception.MobileException;
import common.service.base.handler.ThreadLocalHandler;
import common.service.contants.MobileConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName MobileInterceptor
 * @Description Todo
 * @Author lixin
 * @Date 2020/02/10 上午10:57
 * Version 0.0.1
 **/
@Slf4j
public class MobileInterceptor  extends HandlerInterceptorAdapter {

    @Autowired
    private MobileSession mobileSession;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
        	log.info("MobileInterceptor request 拒绝: param method:{},URL:{}",request.getMethod(),request.getRequestURL());
            return  true;
        }
        log.info("MobileInterceptor : param method:{},URL:{}",request.getMethod(),request.getRequestURL());
        HandlerMethod handlerMethod=(HandlerMethod) handler;
        Method method=handlerMethod.getMethod();
        
        if (method.getAnnotation(CmsCheckSession.class) != null) {
            String mobileHeader = request.getHeader(MobileConfig.MOBILE_REQ_HEADER_STR);
            log.info("CMSInterceptor 请求头 mobileHeader：" + mobileHeader);
            ReqHeader reqHeader = JSON.parseObject(mobileHeader, ReqHeader.class);
            if (reqHeader == null) {
            	log.info("CMSInterceptor 请求头 reqHeader：is null");
                throw new MobileException(MobileConfig.MOBILE_STATUS_NO_LOGIN, MobileConfig.MOBILE_MSG_NO_LOGIN);
            }
            log.info("CMSInterceptor 请求头 reqHeader：" + JSON.toJSONString(reqHeader));
            String token = reqHeader.getTOKEN();
            // 校验token是否失效
            if (StringUtils.isBlank(token)) {
            	log.info("CMSInterceptor 请求头 token：is null");
                throw new MobileException(MobileConfig.MOBILE_STATUS_NO_LOGIN, MobileConfig.MOBILE_MSG_NO_LOGIN);
            }
            ThreadLocalHandler.setThreadLocal(MobileConfig.SESSION_NAME, token.substring(0, 96));
            ThreadLocalHandler.setThreadLocal(MobileConfig.HTTP_SERVELET_REQUEST, request);
            SessionInfo sessionInfo = (SessionInfo) mobileSession.getAttribute(MobileConfig.SESSION_USR_INFO, 30*24*60*60);
            if (sessionInfo == null) {
            	log.info("CMSInterceptor 用户信息 sessionInfo：is null");
                throw new MobileException(MobileConfig.MOBILE_STATUS_NO_LOGIN, MobileConfig.MOBILE_MSG_NO_LOGIN);
            }
            log.info("CMSInterceptor 用户信息 sessionInfo：" + JSON.toJSONString(sessionInfo));
            if (!Constant.CMS_TOKEN_CODE.equals(sessionInfo.getCode())) {
                throw new MobileException(MobileConfig.MOBILE_STATUS_NO_LOGIN, MobileConfig.MOBILE_MSG_NO_LOGIN);
            }
            return true;
        } 
        
        if(method.getAnnotation(NoCheckSession.class)==null){
            String mobileHeader = request.getHeader(MobileConfig.MOBILE_REQ_HEADER_STR);
            log.info("MobileInterceptor 请求头 mobileHeader："+mobileHeader);
            ReqHeader reqHeader = JSON.parseObject(mobileHeader, ReqHeader.class);
            log.info("MobileInterceptor 请求头 mobileHeader："+mobileHeader);
            if(reqHeader!=null){
            	log.info("MobileInterceptor 请求头 reqHeader："+JSON.toJSONString(reqHeader));
                String token = reqHeader.getTOKEN();
                //校验token是否失效
                if(StringUtils.isNotBlank(token)){
                	log.info("MobileInterceptor 请求头 token："+token);
                    ThreadLocalHandler.setThreadLocal(MobileConfig.SESSION_NAME,token.substring(0,96));
                    ThreadLocalHandler.setThreadLocal(MobileConfig.HTTP_SERVELET_REQUEST,request);
                }else{
                	log.info("MobileInterceptor 请求头 token：is null");
                    throw new MobileException(MobileConfig.MOBILE_STATUS_NO_LOGIN,MobileConfig.MOBILE_MSG_NO_LOGIN);
                }
                SessionInfo sessionInfo = (SessionInfo) mobileSession.getAttribute(MobileConfig.SESSION_USR_INFO);
                if(sessionInfo ==null){
                	log.info("MobileInterceptor 用户信息 sessionInfo：is null");
                    throw new MobileException(MobileConfig.MOBILE_STATUS_NO_LOGIN,MobileConfig.MOBILE_MSG_NO_LOGIN);
                }
                log.info("MobileInterceptor 用户信息 sessionInfo："+JSON.toJSONString(sessionInfo));
                if (StringUtils.isNotBlank(sessionInfo.getCode())) {
                    throw new MobileException(MobileConfig.MOBILE_STATUS_NO_LOGIN, MobileConfig.MOBILE_MSG_NO_LOGIN);
                }
                return true;
            }else {
            	log.info("MobileInterceptor 请求头 reqHeader：is null");
                throw new MobileException(MobileConfig.MOBILE_STATUS_NO_LOGIN,MobileConfig.MOBILE_MSG_NO_LOGIN);
            }

        }else {
            String mobileHeader = request.getHeader(MobileConfig.MOBILE_REQ_HEADER_STR);
            log.info("MobileInterceptor 请求头 mobileHeader："+mobileHeader);
            ReqHeader reqHeader = JSON.parseObject(mobileHeader, ReqHeader.class);
            if(reqHeader!=null){
                String token = reqHeader.getTOKEN();
                //校验token是否失效
                if(StringUtils.isNotBlank(token)){
                	log.info("MobileInterceptor 请求头 token："+token);
                    ThreadLocalHandler.setThreadLocal(MobileConfig.SESSION_NAME,token.substring(0,96));
                    ThreadLocalHandler.setThreadLocal(MobileConfig.HTTP_SERVELET_REQUEST,request);
                }
            }
            return true;
        }

    }




    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalHandler.removeThreadLocal();
        super.afterCompletion(request, response, handler, ex);
    }
}
